import io from "socket.io-client"
import layoutStore from "@/store/index"

export class SocketIOService {
    private socketURL: any
    private socket: any
    private isConnected: boolean = false
    private msgList: any = []
    private friendRequestList: any = []
    private userId: string
    private layoutSe: any = null

    constructor(data: any = {}, url: string = import.meta.env.VITE_BASE_SOCKET_URL) {
        const { userId } = data
        this.userId = userId
        this.socketURL = url
        this.layoutSe = layoutStore()
    }

    initSocket(data: any = {}, url: string = import.meta.env.VITE_BASE_SOCKET_URL) {
        return new Promise((resolve, reject) => {
            this.socket = io(url, {
                query: {
                    userId: this.userId
                }
            })
            // 连接
            this.socket.on("connect", (data: any) => {
                this.isConnected = this.socket?.connected ?? false
                if(this.isConnected) {
                    resolve(this.socket)
                } else {
                    reject(data)
                }
            })
            // 接收服务端消息
            this.socket.on("reviceConnect", (data: any) => {
                console.log('reviceConnect', data)
                // this.friendList = data
            })
            this.socket.on("reviceMsg", (data: any) => {
                console.log('reviceMsg', data)
                // this.friendRequestList = data
                // this.layoutSe.setFriendRequestList(this.friendRequestList)
            })
            // 接收添加好友请求
            this.socket.on("friendRequest", (data: any) => {
                console.log('friendRequest', data)
                this.friendRequestList = data
                this.layoutSe.setFriendRequestList(this.friendRequestList)
            })
            // 接收服务端断开消息
            this.socket.on("disconnect", (data: any) => {
                this.isConnected = this.socket?.connected ?? false
            })
        })
    }

    // 向服务端发送消息
    sendMsg(data: any) {
        console.log('sendMsg', data)
        this.socket.emit("sendMsg", data)
    }
    // 与服务端断开连接
    disconnect() {
        this.socket.disconnect()
        console.log('disconnect')
    }
}